/*
 * @Author: your name
 * @Date: 2021-05-19 17:47:55
 * @LastEditTime: 2021-06-01 19:34:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/staff/index.tsx
 */
import { IForm } from '@/components/form/interface';
import {
  Button,
  Card,
  Space,
  Table,
  Tag,
  Modal,
  TablePaginationConfig,
  Col,
  Row,
  Popover,
} from 'antd';
import React, { useState } from 'react';
import RechargeModal from './rechargeModal';
import RechargeSpendHistory from './rechargeSpendHistory';
import VipModal from './vipModal';
import GoodsModal from './vipModal';
import { FormOutlined, DeleteOutlined } from '@ant-design/icons';
import { IFormTypeEnum } from '@/components/form/formComponent';
import HeaderForm from '@/components/form';
import { PlusOutlined, RedEnvelopeOutlined } from '@ant-design/icons';
import { delete_user, get_user_list } from '@/services/pages';
import initPagination from '@/use/initPagination';
import useObj from '@/use/useObj';
import { useRequest } from 'umi';
import { formatDateTime } from '../../utils/utils';
import { ISex, VipLevel, VipLevelList } from '../../enum/index';
import moment from 'moment';
interface IProps {}
import './index.less';
import { useEffect } from 'react';
import _ from 'lodash';
import { FileSearchOutlined } from '@ant-design/icons';
const Vip = (props: IProps) => {
  const [obj, setObj] = useObj({
    ...initPagination,
    visible: false,
    refresh: null,
    row: null,
    search: '',
  });
  const [visible, setVisible] = useState(false);
  const [rechargeVisible, setRechargeVisible] = useState(false);
  const [rechargeSpendVisible, setRechargeSpendVisible] = useState(false);

  const { data, error, loading } = useRequest(
    () =>
      get_user_list({
        page_size: obj.pagination.pageSize,
        page_num: obj.pagination.current,
        search: obj.search,
      }),
    {
      refreshDeps: [obj.pagination, obj.refresh, obj.search],
    },
  );
  const getVipLevelLabel = (id: number) => {
    console.log(VipLevelList, 'VipLevelList==');

    return VipLevelList.find((r) => r.key === id)?.label;
  };
  const columns: IForm[] = [
    {
      key: 'user_name',
      dataIndex: 'user_name',
      title: '姓名',
    },
    {
      key: 'sex',
      dataIndex: 'sex',
      title: '性别',
      render: (text) => {
        return ISex[text as keyof typeof ISex];
      },
    },
    {
      key: 'birthday',
      dataIndex: 'birthday',
      title: '出生日期',
      render: (text) => {
        return moment(Number(text) * 1000).format('YYYY-MM-DD');
      },
    },
    {
      key: 'mobile',
      dataIndex: 'mobile',
      title: '手机号码',
    },
    {
      key: 'balance',
      dataIndex: 'balance',
      title: '账户余额(元)',
      render: (text) => {
        return <span>{text / 100}</span>;
      },
    },
    {
      key: 'vip_level',
      dataIndex: 'vip_level',
      title: '会员等级',
      render: (text) => {
        return <span>{getVipLevelLabel(text) || '未设置'}</span>;
      },
    },
    {
      key: 'create_time',
      dataIndex: 'create_time',
      title: '创建时间',
      render: (text) => {
        return formatDateTime(text);
      },
    },
    {
      key: 'vip_rights',
      dataIndex: 'vip_rights',
      title: '权益',
      render: (text) => {
        const list = JSON.parse(text);
        if (list?.length > 0) {
          return (
            <Popover
              title="会员权益"
              overlayStyle={{ width: 400 }}
              content={
                <div>
                  <Row style={{ padding: 5, fontWeight: 550 }}>
                    <Col span={10}>项目名称</Col>
                    <Col span={8}>可用门店</Col>
                    <Col span={6}>可用次数</Col>
                  </Row>

                  {_.map(list, (row, index) => {
                    return (
                      <Row
                        key={index}
                        style={{ padding: 5, borderTop: '1px solid #eee' }}
                      >
                        <Col span={10}>{row.project_name}</Col>
                        <Col span={8}>{row.store_name}</Col>
                        <Col span={6}>{row.count}</Col>
                      </Row>
                    );
                  })}
                </div>
              }
            >
              <Tag color="#87d068">权益详情</Tag>
            </Popover>
          );
        }
        return <Tag>无权益</Tag>;
      },
    },
    {
      key: 'opt',
      dataIndex: 'opt',
      title: '操作',
      render: (text, record) => {
        return (
          <Space>
            {/* <Button
              type="primary"
              onClick={() => {
                setRechargeSpendVisible(true);
              }}
            >
              历史记录
            </Button> */}
            <Button
              type="primary"
              // icon={<FormOutlined />}
              onClick={() => {
                setRechargeVisible(true);
                setObj({ row: record });
              }}
            >
              充值
            </Button>
            <Button
              type="primary"
              // icon={<FormOutlined />}
              onClick={() => {
                setVisible(true);
                setObj({ row: record });
              }}
            >
              编辑
            </Button>
            <Button
              type="primary"
              // icon={<DeleteOutlined />}
              danger
              onClick={() => deleteVip(record.user_id)}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    setObj((obj) => {
      obj.pagination.total = data?.results[0]?.total || 0;
    });
  }, [data]);

  const deleteVip = (id: number) => {
    Modal.confirm({
      title: '删除操作！',
      content: '你确定要删除该条数据？',
      onOk: async () => {
        await delete_user({ user_id: id });
        setObj((obj) => {
          obj.pagination.current = 1;
          obj.refresh = Symbol();
        });
      },
    });
  };

  const List = [
    {
      key: 'search',
      type: IFormTypeEnum.Input,
      label: '用户名/手机号',
    },
  ];

  return (
    <Card title="会员管理" className="vip">
      <div className="flex-between">
        <HeaderForm
          list={List}
          layout="inline"
          style={{ margin: '10px 0' }}
          onSubmit={(form) => setObj({ search: form.search })}
        />
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setVisible(true);
              setObj({ row: null });
            }}
          >
            添加会员
          </Button>
          {/* <Button
            type="primary"
            icon={<RedEnvelopeOutlined />}
            onClick={() => {
              setRechargeVisible(true);
            }}
          >
            充值
          </Button> */}
        </Space>
      </div>
      <Table
        rowKey={(record) => record.user_id}
        loading={loading}
        columns={columns}
        dataSource={data?.results}
        pagination={obj.pagination}
        onChange={(pagination: TablePaginationConfig): void => {
          const { current, pageSize } = pagination;
          setObj((obj: any) => {
            obj.pagination.current = current;
            obj.pagination.pageSize = pageSize;
            obj.onReFresh = Symbol();
          });
        }}
      />
      {visible && (
        <VipModal
          visible={visible}
          row={obj.row}
          close={() => setVisible(false)}
          refresh={() => {
            setObj((obj) => {
              obj.pagination.current = 1;
              obj.refresh = Symbol();
            });
          }}
        />
      )}
      {rechargeVisible && (
        <RechargeModal
          row={obj.row}
          visible={rechargeVisible}
          close={() => setRechargeVisible(false)}
          refresh={() => {
            setObj((obj) => {
              obj.pagination.current = 1;
              obj.refresh = Symbol();
            });
          }}
        />
      )}
      {rechargeSpendVisible && (
        <RechargeSpendHistory
          visible={rechargeSpendVisible}
          close={() => setRechargeSpendVisible(false)}
        />
      )}
    </Card>
  );
};
export default Vip;
